package com.geralt.im.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.Socket;

import javax.swing.JOptionPane;

import com.geralt.im.controller.Controller;
import com.geralt.im.protocol.Request;
import com.geralt.im.protocol.Response;

public class ObjectClientThread extends ClientReaderRunnable {
	

	InputStream is = null;
	ObjectInputStream ois = null;
	ObjectOutputStream oos = null;
	OutputStream os = null;
	private static ObjectClientThread instance;

	private ObjectClientThread(Socket socket) {
		super(socket);
		
		try {
			os = socket.getOutputStream();
			oos = new ObjectOutputStream(os);
			is = socket.getInputStream();
			ois = new ObjectInputStream(is);
		} catch (IOException e) {
			// closeSocket();
			e.printStackTrace();
		}
	}

	public void run() {

		try {
			while (IMClient.flag) {
				read();
			}
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null, "Can't connect to Server");
			closeSocket();
		}
		if (is != null) {
			closeSocket();
		}
	}

	public void write(Object request) {
		try {
			oos.writeObject(request);
			System.out.println(request);
		} catch (IOException e) {
			JOptionPane.showMessageDialog(null, "Can't connect to Server");
			closeSocket();
		}
	}

	public Response read() throws ClassNotFoundException, IOException {
		Response rs = null;
		rs = (Response) ois.readObject();
		Controller.getInstance().excute(rs);
		return rs;
	}

	public void closeSocket() {
		try {
			is.close();
			ois.close();
			if (os != null) {
				os.close();
				oos.close();
			}
			socket.close();
		} catch (IOException e) {
			// e.printStackTrace();
		}
	}

	public synchronized static ObjectClientThread getInstance(Socket socket) {
		if (instance == null) {
			instance = new ObjectClientThread(socket);
		}
		return instance;
	}
}
